layui.use(['form','layer','laydate','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    //新闻列表
    var tableIns = table.render({
        elem: '#newsList',
        url:"/news/article?method=getArticleByUser",
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limit : 10000,
        limits : [10,15,20,25,10000],
        id : "newsListTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'id', title: 'ID', width:60, align:"center"},
            {field: 'textId', title: '文章id'},
            {field: 'categoryId', title: '分类id'},
            {field: 'categoryName', title: '文章类别',width: 150},
            {field: 'title', title: '文章标题', width:400},
            {field: 'author', title: '发布者', align:'center'},
            {field: 'createTimeStr', title: '投稿日期', align:'center'},
            {field: 'isCheck', title: '是否通过审核', align:'center', templet:'#newsIsCheckBox',width: 150},
            {title: '操作',width:150, templet:'#newsListBar',fixed:"right",align:"center"}
        ]],done: function () {
            $("[data-field='id']").css('display','none');
            $("[data-field='textId']").css('display','none');
            $("[data-field='categoryId']").css('display','none');
        },
        response: {
            statusCode: 200 //规定成功的状态码，默认：0
        }
    });

    form.on('switch(newsCheck)', function(data){
        //获取新状态值
        var newState = data.elem.checked?1:0;
        console.log(newState)
        //获取所需属性值
        let article_id = data.elem.attributes['article_id'].nodeValue;
        console.log(article_id)
        var params = {}
        params.id = article_id;
        params.isCheck = newState;
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        $.ajax({
            url: API_BASE_URL + '/article?method=changeCheck',
            method: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            data: JSON.stringify(params),
            success(res) {
                console.log(res.code)
                if (res.code == 200) {


                    setTimeout(function(){
                        layer.close(index);
                        if(data.elem.checked){
                            layer.msg("审核成功！");
                        }else{
                            layer.msg("取消审核成功！");
                        }
                    },500);
                        //刷新父页面

                }else{
                    layer.msg(res.msg);
                }
            }
        })


        // setTimeout(function(){
        //     layer.close(index);
        //     if(data.elem.checked){
        //         layer.msg("审核成功！");
        //     }else{
        //         layer.msg("取消审核成功！");
        //     }
        // },500);
    })

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            table.reload("newsListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    //添加、编辑文章
    function addNews(edit){
        var index = layui.layer.open({
            title : "添加文章",
            type : 2,
            content : "newsAdd.html",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                if(edit){
                    body.find(".id").val(edit.id);
                    body.find(".newsName").val(edit.title);
                    body.find(".author").val(edit.author);
                    body.find(".thumbImg").attr("src",edit.img_url);
                    body.find("#news_content").text(edit.text);
                    body.find("#news_content").attr("disabled","disabled")
                    body.find(".textId").val(edit.textId);
                    body.find("#newsStatus").val(edit.isShow);
                    body.find("#newsStatus").attr("disabled","disabled");
                    body.find("#category").attr('data-id',edit.categoryId);
                    body.find("#category").attr("disabled","disabled");
                    let inputs = body.find("input")
                    console.log(inputs)
                    inputs.each(function (){
                        $(this).addClass("layui-disabled")
                    });
                    form.render('select');
                    form.render();
                }
                setTimeout(function(){
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(index);
        })
    }
    $(".addNews_btn").click(function(){
        addNews();
    })

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('newsListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的文章？', {icon: 3, title: '提示信息'}, function (index) {
                // $.get("删除文章接口",{
                //     newsId : newsId  //将需要删除的newsId作为参数传入
                // },function(data){
                tableIns.reload();
                layer.close(index);
                // })
            })
        }else{
            layer.msg("请选择需要删除的文章");
        }
    })

    //列表操作
    table.on('tool(newsList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            addNews(data);
        } else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此文章？',{icon:3, title:'提示信息'},function(index){
                $.get(API_BASE_URL+'/article?method=delete',{
                    newsId : data.newsId  //将需要删除的newsId作为参数传入
                },function(data){
                    tableIns.reload();
                    layer.close(index);
                })
            });
        } else if(layEvent === 'look'){ //预览
            parent.location.href = "/news/content.html?id="+data.id;
        }
    });

})



